package cn.edu.scau.cmi.liuxintong;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class HibernataClient extends Application{
	static TextArea textArea = new TextArea();
	String read;
	@Override
	public void start(Stage primaryStage) throws Exception {
		// TODO Auto-generated method stub
		AnchorPane anchorPane = new AnchorPane();
		DropShadow dropshadow = new DropShadow();
		dropshadow.setColor(Color.PALEVIOLETRED);
		dropshadow.setOffsetX(5.0);
		dropshadow.setOffsetY(5.0);
		dropshadow.setRadius(10.0);
		Text experimentName = new Text("Hibernate框架实验");//ok
		experimentName.setEffect(dropshadow);
		experimentName.setFont(Font.font(" Verdana",FontPosture.ITALIC,40));
	    String[] greetings=new String[] {"请选择实现功能","1.添加学生","2.修改学生","3.删除学生","4.添加教师"
	    ,"5.修改教师","6.删除教师","7.学生选择指导教师","8.学生修改指导教师","9.教师选择被指导的学生",
	    "10.教师修改被指导的学生","11.显示学生和教师信息"};
	    ChoiceBox<String> choiceBox = new ChoiceBox((FXCollections.observableArrayList("请选择实现功能","1.添加学生","2.修改学生","3.删除学生","4.添加教师"
	    ,"5.修改教师","6.删除教师","7.学生选择指导教师","8.学生修改指导教师","9.教师选择被指导的学生",
	    "10.教师修改被指导的学生","11.显示学生和教师信息")));
	    choiceBox.getSelectionModel().select(0);
		TextField textField = new TextField();
		textArea.setPrefHeight(330);
	    textArea.setPrefWidth(780);
	    anchorPane.getChildren().addAll(experimentName,textField,choiceBox,textArea);
		choiceBox.getSelectionModel().selectedIndexProperty().addListener(
	    		(ObservableValue<? extends Number> ov,
	    				Number old_val,Number new_val)->{
	    					switch(greetings[new_val.intValue()]) {
	    					case "请选择实现功能":
	    						textArea.appendText("请选择实现功能\n");
	    						break;
	    					case "1.添加学生":
	    						textArea.appendText("请输入要添加学生姓名:\n");
	    						read=textField.getText();
	    						newStudent(read);
	    				        listStudents();
	    				        break; 
	    					case "2.修改学生":
	    						 textArea.appendText("请输入要修改学生id和姓名:\n");
	    						 read=textField.getText();
	    				          String[] temp=read.split(" ");
	    				          changeStudent(temp[0],temp[1]);
	    				          listStudents();
	    				          break;
	    					case "3.删除学生":
	    						  textArea.appendText("请输入要删除学生id:\n");
	    						  read=textField.getText();
	    				          delectStudent(read);
	    				          listStudents();
	    				          break;
	    					case "4.添加教师":
	    						textArea.appendText("请输入要添加老师姓名:\n");
	    						 read=textField.getText();
	    				          newTeacher(read);
	    				          listTeacher();
	    				          break;
	    					case "5.修改教师":
	    						textArea.appendText("请输入要修改老师id和姓名:\n");
	    						read=textField.getText();
	    			            String[] temp1=read.split(" ");
	    			            changeTeacher(temp1[0],temp1[1]);
	    			            listTeacher();
	    			            break;
	    					case "6.删除教师"	:
	    						textArea.appendText("请输入要删除老师id\n");
	    						read=textField.getText();
	    				         delectTeacher(read);
	    				         listTeacher();
	    				          break;
	    					case "7.学生选择指导教师":
	    						textArea.appendText("请输入学生的id和选择老师的id\n");
	    						read=textField.getText();
	    			               String[] temp2=read.split(" ");
	    			               chooseTutorTeacher(temp2[0],temp2[1]);
	    			               break;
	    					case "8.学生修改指导教师":
	    						textArea.appendText("请输入学生的id和新指导老师的id\n");
	    						read=textField.getText();
	    			              String[] temp3=read.split(" ");
	    			              changeTutorTeacher(temp3[0],temp3[1]);
	    					       break;	
	    					case "9.教师选择被指导的学生":
	    						textArea.appendText("请输入老师id和被指导学生id\n");
	    						read=textField.getText();
	    			               String[] temp4=read.split(" ");
	    			               changeBeTutorStudent(temp4[0],temp4[1]);
	    			               break;
	    					case "10.教师修改被指导的学生":
	    						textArea.appendText("请输入老师id和需要修改被指导学生id\n");
	    						read=textField.getText();
	    			               String[] temp5=read.split(" ");
	    			               changeTutorStudent(temp5[0],temp5[1]);
	    			               break;
	    					case "11.显示学生和教师信息":
	    						listStudents();    
	    		                listTeacher();
	    		                break;
	    					}
	    				});
	     AnchorPane.setLeftAnchor(experimentName, 275.0);
		 AnchorPane.setBottomAnchor(experimentName,400.0);//下
		 AnchorPane.setLeftAnchor(textField, 450.0);
		 AnchorPane.setBottomAnchor(textField,350.0);//下
		 AnchorPane.setLeftAnchor( choiceBox, 150.0);
		 AnchorPane.setBottomAnchor( choiceBox,350.0);//下
		 AnchorPane.setLeftAnchor(textArea, 10.0);
		 AnchorPane.setBottomAnchor(textArea,10.0);
		 primaryStage.setScene(new Scene(anchorPane, 800,450));
	     primaryStage.show();
	}
	public static void main(String[] args) {
		 launch(args);
	  }
	 public static void changeTutorStudent(String teacherId,String studentId) {
		 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
		 Transaction tran = session.beginTransaction();
		 StudentDAO studentDAO=new StudentDAO();
	     Student student = studentDAO.findById(Long.parseLong(studentId));
	     TeacherDAO teachertDAO=new TeacherDAO();
		 Teacher teacher=teachertDAO.findById(Long.parseLong(teacherId));
		 student.setTeacher(null);
		 studentDAO.change(student);
		 Set students=teacher.getStudents();
		 for(Object s:students) {//设置该老师指导的学生指导老师为空
		     ((Student) s).getId().equals(student.getId());
		     students.remove(s);
		     break;
		 }
		 teacher.setStudents(students);
		 teachertDAO.change(teacher);
	     tran.commit();
	     session.close();
	 }
        public static void changeBeTutorStudent(String teacherId,String studentId) {
        	 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 StudentDAO studentDAO=new StudentDAO();
		     Student student=studentDAO.findById(Long.parseLong(studentId));
		     TeacherDAO teachertDAO=new TeacherDAO();
			 Teacher teacher=teachertDAO.findById(Long.parseLong(teacherId));
			 student.setTeacher(teacher);
		     studentDAO.change(student);
		     Set students=teacher.getStudents();
		     students.add(student);
		     teacher.setStudents(students);
		     teachertDAO.change(teacher);
		     tran.commit();
		     session.close();
        }
	    public static void changeTutorTeacher(String studentId,String teacherId) {
	    	 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 StudentDAO studentDAO=new StudentDAO();
			 Student student=studentDAO.findById(Long.parseLong(studentId));
		     TeacherDAO teachertDAO=new TeacherDAO();
			 Teacher newteacher=teachertDAO.findById(Long.parseLong(teacherId));
			 Teacher oldteacher=student.getTeacher();
			 student.setTeacher(newteacher);
			 studentDAO.change(student);
		     Set newTescherStudents=newteacher.getStudents();
		     newTescherStudents.add(student);
		     newteacher.setStudents(newTescherStudents);
		     teachertDAO.change(newteacher);
		     Set oldTescherStudents=newteacher.getStudents();
		     for(Object s:oldTescherStudents) {//设置该老师指导的学生指导老师为空
			     ((Student) s).getId().equals(student.getId());
			     oldTescherStudents.remove(s);
			     break;
			 }
		     oldteacher.setStudents(oldTescherStudents);
		     teachertDAO.change(oldteacher);
		     tran.commit();
		     session.close();
	     }
		public static void chooseTutorTeacher(String studentId,String teacherId) {
			 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 StudentDAO studentDAO=new StudentDAO();
		     Student student=studentDAO.findById(Long.parseLong(studentId));
		     TeacherDAO teachertDAO=new TeacherDAO();
			 Teacher teacher=teachertDAO.findById(Long.parseLong(teacherId));
		     student.setTeacher(teacher);
		     studentDAO.change(student);
		     Set students=teacher.getStudents();
		     students.add(student);
		     teacher.setStudents(students);
		     teachertDAO.change(teacher);
		     tran.commit();
		     session.close();
		}
        public static void newTeacher(String name) {
	    	  Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
		      Transaction transaction = session.beginTransaction();
		      Teacher teacher=new Teacher();
		      teacher.setName(name);
		      TeacherDAO teachertDAO=new TeacherDAO();
		      teachertDAO.save(teacher);
		      transaction.commit();
		      session.close();
	    }
        public static void changeTeacher(String id,String name) {
        	Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 TeacherDAO teachertDAO=new TeacherDAO();
			 Teacher teacher=teachertDAO.findById(Long.parseLong(id));
			 teacher.setName(name);
			 teachertDAO.change(teacher);
			 tran.commit();
		      session.close();
        }
         public static void delectTeacher(String id) {
        	 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 TeacherDAO teachertDAO=new TeacherDAO();
			 Teacher teacher=teachertDAO.findById(Long.parseLong(id));
			 Set students=teacher.getStudents();
			 for(Object s:students) {//设置该老师指导的学生指导老师为空
			     ((Student) s).setTeacher(null);
			     StudentDAO studentDAO =new StudentDAO();
				studentDAO.change(((Student) s));
			 }
			 teacher.setStudents(null);
			 teachertDAO.delete(teacher);
			 tran.commit();
		     session.close();
	}

         public static void listTeacher() {
        	 textArea.appendText("老师名单为：\n");
	    	TeacherDAO teacherDAO=new TeacherDAO();
	 	    List teachers = teacherDAO.findAll();
	 	    Iterator<?> teacherIterator = teachers.iterator();
	 	    while(teacherIterator.hasNext()){
	 	    	Teacher teacher = (Teacher) teacherIterator.next();
	 	    	textArea.appendText("老师的ID号是："+teacher.getId()+"老师的名字是："+teacher.getName()+"老师指导的学生:");
	 	      Set students=teacher.getStudents();
	 	      if(students.size()!=0) {
	 	    	   for(Object s:students) {//设置该老师指导的学生指导老师为空
	 	    		  textArea.appendText(((Student) s).getId()+" ");
			 }
	 	      }
	 	      else textArea.appendText("null");
	 	     textArea.appendText("\n");
	 	    }
		
	     }
		public static  void newStudent(String name) {
	      Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
	      Transaction transaction = session.beginTransaction();
	      Student student=new Student();
	      student.setName(name);
	      StudentDAO studentDAO=new StudentDAO();
	      studentDAO.save(student);
	      transaction.commit();
	      session.close();
	    }
		public static void changeStudent(String id, String name) {
			 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 StudentDAO studentDAO=new StudentDAO();
		     Student student=studentDAO.findById(Long.parseLong(id));
		     student.setName(name);
		     studentDAO.change(student);
		     tran.commit();
		     session.close();
		}
		public static void delectStudent(String id) {
			 Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
			 Transaction tran = session.beginTransaction();
			 StudentDAO studentDAO=new StudentDAO();
		     Student student=studentDAO.findById(Long.parseLong(id));
		     studentDAO.delete(student);
		     tran.commit();
		     session.close();
   }
        public static void listStudents() {
	    textArea.appendText("学生名单为：\n");
	    StudentDAO studentDAO=new StudentDAO();
	    List students = studentDAO.findAll();
	    Iterator<?> studentIterator = students.iterator();
	    while(studentIterator.hasNext()){
	      Student student = (Student) studentIterator.next();
	      if(student.getTeacher()!=null) {
	    	  textArea.appendText("学生的ID号是："+student.getId()+"学生的名字是："+student.getName()+"学生指导老师"+student.getTeacher().getId());	
	    	  textArea.appendText("\n");
	      }
	      else {
	    	  textArea.appendText("学生的ID号是："+student.getId()+"学生的名字是："+student.getName()+"学生指导老师"+student.getTeacher());
	    	  textArea.appendText("\n");
	      }
	    }
	  }
}
